package com.test23213;

import java.lang.reflect.Field;

import org.json.JSONObject;

public class CustomJSON {

    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
        // 创建一个示例对象
        Person person = new Person("John", 25, new Address("123 Main St", "City"));
        person.x = person;

        System.out.println(covertoJSON(person));
        // 递归遍历对象的属性

    }

    private static JSONObject traverseObjectProperties(Object obj, int depth)
            throws IllegalArgumentException, IllegalAccessException {
        // 获取对象的类
        if (depth > 10) {
            return null;
        }
        JSONObject jsonObject = new JSONObject();

        Class<?> objClass = obj.getClass();
        for (java.lang.reflect.Field field : objClass.getDeclaredFields()) {
            field.setAccessible(true);

            Object value = field.get(obj);

            if (value != null && !value.getClass().isPrimitive()
                    && !value.getClass().getName().startsWith("java.lang")) {
                jsonObject.put(field.getName(), traverseObjectProperties(value, depth + 1));

            } else {
                jsonObject.put(field.getName(), value);
            }
        }
        return jsonObject;

    }

    public  static String covertoJSON(Object x) {
        try {

            return traverseObjectProperties(x, 0).toString();
        } catch (Exception e) {
            return "";
            // TODO: handle exception
        }
    }

    // 示例类
    static class Person {
        private String name;
        private int age;
        private Address address;
        private Person x;

        public Person(String name, int age, Address address) {
            this.name = name;
            this.age = age;
            this.address = address;
        }

        public void setPerson(Person x) {
            this.x = x;
        }
    }

    static class Address {
        private String street;
        private String city;

        public Address(String street, String city) {
            this.street = street;
            this.city = city;
        }
    }
}
